package top.jle.jpa.basic.util;

import top.jle.jpa.basic.exception.BasicCustomException;
import top.jle.jpa.basic.exception.BasicExceptionCode;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.function.Supplier;

/**
 * 关于异常的工具类
 */
public class ExceptionUtils {

	private ExceptionUtils(){}
	/**
	 * 将CheckedException转换为UncheckedException.
	 */
	public static RuntimeException unchecked(Exception e) {
		if (e instanceof RuntimeException re) {
			return  re;
		} else {
			return new RuntimeException(e);
		}
	}

	/**
	 * 将ErrorStack转化为String.
	 */
	public static String getStackTraceAsString(Exception e) {
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}

	public static Supplier<BasicCustomException> build(Enum<?> exceptionEnum){
		return ()->new BasicCustomException(exceptionEnum);
	}
	public static Supplier<BasicCustomException> buildForInvalidParam(){
		return build(BasicExceptionCode.INVALID_PARAM);
	}
	public static void throwException(Enum<?> exceptionEnum) throws BasicCustomException{
		throw new BasicCustomException(exceptionEnum);
	}
	public static void throwException(String code) throws BasicCustomException{
		throw new BasicCustomException(code);
	}
	public static void throwInvalidParamException() throws BasicCustomException{
		throwException(BasicExceptionCode.INVALID_PARAM);
	}
}
